<!-- 配置初始页面 -->
<template>
    <div class="Home min-h-screen w-full">
      <header>
        <Navbar/>
      </header>
      <main class="main-container">
        <div class="cityInput relative">
          <input type="text" v-model="inputValue" @input="handleInputChange" placeholder="请输入城市名称" class="py-2 px-1 w-full bg-transparent border-b focus:border-none outline-none focus:shadow-md text-white"/>
          <ul class="absolute bg-weather-secondary text-white w-full shadow-md py-2 px-1 top-[62px]" v-if="apiStore.inputValue">
            <p v-if="!apiStore.cityMessage&&apiStore.inputValue">似乎没有找到你查找的城市</p>
            <li v-else class="py-2 cursor-pointer" @click="handleLiClick()">
              <template v-if="apiStore.cityMessage[0].district.length>0">
                {{ apiStore.cityMessage[0].district }}
              </template>
              <template v-else-if="apiStore.cityMessage[0].city.length>0">
                {{ apiStore.cityMessage[0].city }}
              </template>
              <template v-else>
                {{ apiStore.cityMessage[0].province }}
              </template>
            </li>
          </ul>
        </div>
          <div class="savedCities-container mt-10 max-h-[300px] overflow-y-auto" v-show="!apiStore.cityMessage">
            <p v-if="!savedCities || savedCities.length === 0" class="empty-message">暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</p>
            <div v-else class="city-list">
              <div v-for="(cityData, index) in savedCities" :key="cityData.id" class="flex message-container justify-between" @mouseover="showButtons(index)" @mouseout="hideButtons(index)">
                <div class="message mb-4 bg-weather-secondary py-2 px-4 flex justify-between cursor-pointer duration-300" :class="{ 'w-4/5': isMouseOver[index], 'w-full': !isMouseOver[index] }">
                  <h3>{{ cityData.city }}</h3>
                  <span>{{ `${cityData.temperature}度` }}</span>
                </div>
                <div class="flex mb-4 gap-2" :class="{ 'hidden': !isMouseOver[index] }">
                  <button class="bg-yellow-500 text-center w-[80px]" @click="handleViewClick(cityData)">查看</button>
                  <button class="bg-yellow-500 text-center w-[80px]" @click="handleDeleteClick(cityData.id)">删除</button>
                </div>
              </div>
            </div>
          </div>
          <h2 class="mt-6 text-white">近期天气</h2>
          <WeatherChart/>
      </main>
    </div>
  </template>
  
  <script>
  import { ref, watch } from 'vue';
  import Navbar from './Navbar.vue';
  import WeatherChart from './WeatherChart.vue';
  import { useAPIStore } from '../store/ApiStore';
  import { useRouter, useRoute } from 'vue-router';
  
  export default {
    components: {
      Navbar,
      WeatherChart,
    },
    setup() {
      const router = useRouter();
      const route = useRoute();
      const savedCities = ref(JSON.parse(localStorage.getItem('savedCities')) || []);
      const apiStore = useAPIStore();
      const inputValue = ref('');
      const loading = ref(false);
  
      // 监听 savedCities 变化，当 savedCities 改变时重新渲染页面
      watch(savedCities, () => {
        // 更新 localStorage 中的 savedCities
        localStorage.setItem('savedCities', JSON.stringify(savedCities.value));
      });
  
      const handleInputChange = async () => {
        loading.value = true; // 设置加载状态为true
        apiStore.inputValue = inputValue.value;
        await apiStore.fetchCityMessage();
        loading.value = false; // 加载完成后设置加载状态为false
      };
  
      const handleLiClick = () => {
        const district = apiStore.cityMessage[0].district;
        const adcode = apiStore.cityMessage[0].adcode;
        const city = apiStore.cityMessage[0].city;
        
        let searchParam = '';
        if (district && district.length > 0) {
          searchParam = `search=${encodeURIComponent(district)}`;
        } else if (city && city.length > 0) {
          searchParam = `search=${encodeURIComponent(city)}`;
        } else {
          searchParam = `search=${encodeURIComponent(apiStore.cityMessage[0].province)}`;
        }
        
        router.push(`/weather/${adcode}?${searchParam}`);
      };
  
      const isMouseOver = ref([]);
  
      const showButtons = (index) => {
        isMouseOver.value[index] = true;
      };
  
      const hideButtons = (index) => {
        isMouseOver.value[index] = false;
      };
  
      const handleViewClick = (cityData) => {
        const adcode = cityData.adcode;
        const city = cityData.city;
        const searchParam = `search=${encodeURIComponent(city)}`;
        router.push(`/weather/${adcode}?${searchParam}`);
      };
  
      const handleDeleteClick = (id) => {
        savedCities.value = savedCities.value.filter(city => city.id !== id);
      };
  
      return {
        inputValue,
        apiStore,
        savedCities,
        handleInputChange,
        handleLiClick,
        isMouseOver,
        showButtons,
        hideButtons,
        handleViewClick,
        handleDeleteClick,
        loading, // 加载状态
      };
    },
  };
  </script>
  
  <style scoped>
  .main-container {
    @apply px-40;
  }
  
  .cityInput {
    @apply pt-4 mb-8;
  }
  
  .input {
    @apply w-full h-10 border-none bg-transparent border-b border-gray-300 text-white text-base placeholder-gray-500 focus:outline-none focus:shadow-lg;
  }
  
  .empty-message {
    @apply text-white;
  }
  
  .city-list {
    @apply p-0 m-0 text-white;
  }
  
  .savedCities-container p {
    @apply text-center;
  }
  
  .loading-message {
    @apply text-white;
  }
  </style>